import axios from 'axios'
import Api from './api/index.js'
import { getToken } from '@/common/auth.js'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { Http_Status_Enum } from '@/common/enum.js'
import useUserStore from '@/stores/user.js'
import useEnterpriseStore from '@/stores/enterprise.js'
import qs from 'qs'

// 是否显示重新登录
let isShowRelogin = false
const instance = axios.create({
  timeout: 60000,
  baseURL: window.domain_config.gateway_server,
})

instance.interceptors.request.use(async (config) => {
  const enterpriseStore = useEnterpriseStore()
  config.headers['Authorization'] = 'Bearer ' + getToken()
  config.headers['tenantId'] = enterpriseStore.enterpriseId
  if (config.method === 'get') {
    const params = {}
    for (const key in config.params) {
      if (config.params[key]) {
        params[key] = config.params[key]
      }
    }
    config.url = config.url + '?' + qs.stringify(params)
    config.params = {}
  }
  return config
})

instance.interceptors.response.use(
  (res) => {
    const config = res.config
    const statusCode = res.data?.code || 200
    // 获取错误信息
    const msg = Http_Status_Enum[statusCode] || res.data.msg || Http_Status_Enum['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    // 登录态过期
    if (statusCode === 401) {
      if (!isShowRelogin) {
        isShowRelogin = true
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            isShowRelogin = false
            useUserStore()
              .logout()
              .then(() => {
                location.href = '/login'
              })
          })
          .catch(() => {
            isShowRelogin = false
          })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (!config.ignoreError) {
      if (statusCode === 500) {
        ElMessage({ message: msg, type: 'error' })
        return Promise.reject(new Error(msg))
      } else if (statusCode === 601) {
        ElMessage({ message: msg, type: 'warning' })
        return Promise.reject(new Error(msg))
      } else if (statusCode !== 200) {
        ElNotification.error({ title: msg })
        return Promise.reject('error')
      }
    }
    return Promise.resolve(res.data)
  },
  (error) => {
    let { message } = error
    if (message == 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  },
)

export default new Api(instance).use()
